﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.ServiceHelper.Excel;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace K.KDL
{
    public class CustomSalListPlugin : AbstractListPlugIn
    {
        #region | Fields  |

        private string _directioy = string.Empty;

        private string _fileName = string.Empty;

        private string _filePath = string.Empty;

        protected SaveFileType _fileType = SaveFileType.XLS;

        private string _outServicePath = string.Empty;

        const string OS_SQL = @"/*dialect*/SELECT '' AS 应收单序号, '销售出库单' AS 源单类型, FBILLNO AS 源单号, FDATE AS 业务日期
                                , OSE.FSEQ AS 行号, M.FNUMBER AS 物料编码, ML.FNAME AS 物料名称, ML.FSPECIFICATION AS 规格型号, CASE M.F_PATC_SFYBSP WHEN 1 THEN '是' ELSE '否' END AS 是否医保
                                , OSER.FARNOTJOINQTY AS 计价数量, U.FNUMBER AS 计价单位, UL.FNAME AS 计价单位名称, OSEF.FPRICE AS 单价, OSEF.FTAXRATE AS 税率, OSEF.FTAXPRICE AS 含税单价
                                , OSEF.FAMOUNT AS 金额, OSEF.FTAXAMOUNT AS 税额, OSEF.FALLAMOUNT AS 价税合计
                                , S.FNUMBER AS 仓库编码, SL.FNAME AS 仓库名称
                                , OSE.FLOT_TEXT AS 批号, OSE.F_PATC_SCPH AS 生产批号, OSE.F_PATC_MJPH AS 灭菌批号
                                , OSE.FPRODUCEDATE AS 生产日期, OSE.FEXPIRYDATE AS 有效期至, OSE.FNOTE AS 备注, OSE.F_PATC_KS AS 科室
                                FROM T_SAL_OUTSTOCK OS
                                INNER JOIN T_SAL_OUTSTOCKENTRY OSE ON OS.FID=OSE.FID
                                INNER JOIN T_SAL_OUTSTOCKENTRY_F OSEF ON OSE.FENTRYID=OSEF.FENTRYID
                                INNER JOIN T_SAL_OUTSTOCKENTRY_R OSER ON OSE.FENTRYID=OSER.FENTRYID
                                INNER JOIN T_BD_MATERIAL M ON OSE.FMATERIALID=M.FMATERIALID
                                INNER JOIN T_BD_MATERIALBASE MB ON M.FMATERIALID=MB.FMATERIALID
                                INNER JOIN T_BD_MATERIAL_L ML ON M.FMATERIALID=ML.FMATERIALID AND ML.FLOCALEID=2052
                                INNER JOIN T_BD_STOCK S ON OSE.FSTOCKID=S.FSTOCKID
                                INNER JOIN T_BD_STOCK_L SL ON S.FSTOCKID=SL.FSTOCKID AND SL.FLOCALEID=2052
								INNER JOIN T_BD_UNIT U ON OSEF.FPRICEUNITID=U.FUNITID
                                INNER JOIN T_BD_UNIT_L UL ON U.FUNITID=UL.FUNITID AND UL.FLOCALEID=2052
                                WHERE OS.FID IN ({0}) AND OSER.FARNOTJOINQTY > 0
                                ORDER BY FBILLNO, FSEQ";

        const string RS_SQL = @"/*dialect*/SELECT '' AS 应收单序号, '销售退货单' AS 源单类型, FBILLNO AS 源单号, FDATE AS 业务日期
                                , RSE.FSEQ AS 行号, M.FNUMBER AS 物料编码, ML.FNAME AS 物料名称, ML.FSPECIFICATION AS 规格型号, CASE M.F_PATC_SFYBSP WHEN 1 THEN '是' ELSE '否' END AS 是否医保
                                , RSER.FARNOTJOINQTY AS 计价数量, U.FNUMBER AS 计价单位, UL.FNAME AS 计价单位名称, RSEF.FPRICE AS 单价, RSEF.FTAXRATE AS 税率, RSEF.FTAXPRICE AS 含税单价
                                , RSEF.FAMOUNT AS 金额, RSEF.FTAXAMOUNT AS 税额, RSEF.FALLAMOUNT AS 价税合计
                                , S.FNUMBER AS 仓库编码, SL.FNAME AS 仓库名称
                                , RSE.FLOT_TEXT AS 批号, RSE.F_PATC_SCPH AS 生产批号, RSE.F_PATC_MJPH AS 灭菌批号
                                , RSE.FPRODUCEDATE AS 生产日期, RSE.FEXPIRYDATE AS 有效期至, RSE.FNOTE AS 备注, '' AS 科室
                                FROM T_SAL_RETURNSTOCK RS
                                INNER JOIN T_SAL_RETURNSTOCKENTRY RSE ON RS.FID=RSE.FID
                                INNER JOIN T_SAL_RETURNSTOCKENTRY_F RSEF ON RSE.FENTRYID=RSEF.FENTRYID
                                INNER JOIN T_SAL_RETURNSTOCKENTRY_R RSER ON RSE.FENTRYID=RSER.FENTRYID
                                INNER JOIN T_BD_MATERIAL M ON RSE.FMATERIALID=M.FMATERIALID
                                INNER JOIN T_BD_MATERIALBASE MB ON M.FMATERIALID=MB.FMATERIALID
                                INNER JOIN T_BD_MATERIAL_L ML ON M.FMATERIALID=ML.FMATERIALID AND ML.FLOCALEID=2052
                                INNER JOIN T_BD_STOCK S ON RSE.FSTOCKID=S.FSTOCKID
                                INNER JOIN T_BD_STOCK_L SL ON S.FSTOCKID=SL.FSTOCKID AND SL.FLOCALEID=2052
								INNER JOIN T_BD_UNIT U ON RSEF.FPRICEUNITID=U.FUNITID
                                INNER JOIN T_BD_UNIT_L UL ON U.FUNITID=UL.FUNITID AND UL.FLOCALEID=2052
                                WHERE RS.FID IN ({0}) AND RSER.FARNOTJOINQTY > 0
                                ORDER BY FBILLNO, FSEQ";

        #endregion

        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);

            if (e.BarItemKey == "tbExpoortOsToAR")
            {
                Export(this.ListView.SelectedRowsInfo.GetPrimaryKeyValues(), OS_SQL);
            }
            if (e.BarItemKey == "tbExpoortRsToAR")
            {
                Export(this.ListView.SelectedRowsInfo.GetPrimaryKeyValues(), RS_SQL);
            }
        }

        #region | Methods for Export |

        void Export(string[] primaryKeys, string sql)
        {
            List<int> columnIndexs = new List<int>();
            ExcelOperation operation = new ExcelOperation(this.View);

            if (primaryKeys.Length == 0)
            {
                this.View.ShowWarnningMessage("请选择行后再执行导出操作");
                return;
            }

            var ds = DBUtils.ExecuteDataSet(Context, string.Format(sql, string.Join(",", primaryKeys)));
            var dt = ds.Tables[0];
            var billGroups = dt.Rows.OfType<DataRow>().GroupBy(_ => _["源单号"].ToString());
            var seq = 1;
            foreach (var billGroup in billGroups)
            {
                foreach (var line in billGroup)
                {
                    line["应收单序号"] = seq.ToString();
                }
                seq++;
            }

            operation.BeginExport();
            operation.FillColumnName(dt.Columns.OfType<DataColumn>().Select(_ => _.ColumnName).ToList(), 0);
            operation.FillColumnName(dt.Columns.OfType<DataColumn>().Select(_ => _.ColumnName).ToList(), 1);
            operation.ExportToFile(dt, null, 0);
            string outServicePath = "";
            string filePath = "";
            this.InitializePath(out filePath, out outServicePath);
            operation.EndExport(filePath, this._fileType);

            if (outServicePath.Length > 0)
            {
                this.DownLoadFile(outServicePath);
            }
        }

        List<ExcelField> InitialExportFields()
        {
            var result = new List<ExcelField>();

            result.Add(new ExcelField()
            {
                Caption = "源单类型",
                FieldName = "SrcFormType",
                ColumnType = typeof(string)
            });

            result.Add(new ExcelField()
            {
                Caption = "源单号",
                FieldName = "SrcBillNo",
                ColumnType = typeof(string)
            });

            result.Add(new ExcelField()
            {
                Caption = "行号",
                FieldName = "LineNo",
                ColumnType = typeof(int)
            });

            result.Add(new ExcelField()
            {
                Caption = "物料编码",
                FieldName = "MaterialNo",
                ColumnType = typeof(string)
            });

            result.Add(new ExcelField()
            {
                Caption = "计价数量",
                FieldName = "Qty",
                ColumnType = typeof(decimal)
            });

            result.Add(new ExcelField()
            {
                Caption = "税率",
                FieldName = "TaxRate",
                ColumnType = typeof(decimal)
            });

            result.Add(new ExcelField()
            {
                Caption = "含税单价",
                FieldName = "TaxPrice",
                ColumnType = typeof(decimal)
            });

            return result;
        }

        protected void DownLoadFile(string url)
        {
            DynamicFormShowParameter param = new DynamicFormShowParameter
            {
                FormId = "BOS_FileDownLoad"
            };
            param.OpenStyle.ShowType = ShowType.Modal;
            param.CustomParams.Add("IsExportData", "true");
            param.CustomParams.Add("url", url);
            View.ShowForm(param);
        }

        private void InitDirectioy()
        {
            string path = this._directioy;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        protected void InitializePath(out string filePath, out string outServicePath)
        {
            this.InitVariable();
            this.InitDirectioy();
            outServicePath = this._outServicePath;
            filePath = this._filePath;
        }

        protected void InitVariable()
        {
            this._directioy = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFilePath");

            string validFileName = PathUtils.GetValidFileName(string.Format("{0}_{1}", View.BillBusinessInfo.GetForm().Name, DateTime.Now.ToString("yyyyMMddHHmmssff")));
            this._fileName = validFileName;
            if (this._fileType == SaveFileType.XLSX)
            {
                validFileName = validFileName + ".xlsx";
            }
            else
            {
                validFileName = validFileName + ".xls";
            }
            this._outServicePath = PathUtils.GetServerPath(KeyConst.TEMPFILEPATH, validFileName);
            this._filePath = PathUtils.GetPhysicalPath(KeyConst.TEMPFILEPATH, validFileName);
        }

        #endregion

        public override void BeforeExportData(BeforeExportDataArgs e)
        {
            base.BeforeExportData(e);
        }
    }
}
